from PySide6.QtCore import QUrl, Qt, QObject, Slot, QMetaObject, Q_ARG,QEventLoop
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QFrame,QVBoxLayout, QHBoxLayout,QPushButton, QLineEdit,QLabel
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWebEngineCore import QWebEnginePage,QWebEngineSettings
from PySide6.QtWebChannel import QWebChannel
from PySide6.QtGui import QIcon
import json
from PySide6.QtWidgets import QFileDialog
from pathlib import Path
import os

class Bridge(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.map_window = parent

    @Slot(float, float)
    def onMapClicked(self, lng, lat):
        # 安全更新 UI
        QMetaObject.invokeMethod(
            self.map_window.input_lng, "setText",
            Qt.QueuedConnection, Q_ARG(str, str(lng))
        )
        QMetaObject.invokeMethod(
            self.map_window.input_lat, "setText",
            Qt.QueuedConnection, Q_ARG(str, str(lat))
        )
        print(f"坐标已接收: {lng}, {lat}")  # 控制台输出确认

class MapWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("地图标记V1.0")

        icon = QIcon("mark.png")  # 替换为你的图标路径
        self.setWindowIcon(icon)
        
        self.browser = QWebEngineView()
        self.browser.settings().setAttribute(QWebEngineSettings.LocalContentCanAccessRemoteUrls, True)
        
        # 配置 QWebChannel
        self.channel = QWebChannel()
        self.bridge = Bridge(self)
        self.channel.registerObject("pyObject", self.bridge)   #创建一个 QWebChannel 实例
        self.browser.page().setWebChannel(self.channel)
        
        # 输入框和按钮
        self.central_widget = QWidget()
        
        self.layout = QHBoxLayout(self.central_widget)

        self.layoutright = QVBoxLayout()

        
        self.input_lng = QLineEdit(placeholderText="经度")
        self.input_lat = QLineEdit(placeholderText="纬度")
        self.input_title = QLineEdit(placeholderText="标记标题")
        self.btn_add = QPushButton("添加标记")
        self.btn_clear = QPushButton("清空标记")
        self.btn_save = QPushButton("保存标记")
        self.btn_load = QPushButton("加载标记")
        
        # 添加搜索输入框和按钮
        self.search_input = QLineEdit(placeholderText="输入标记标题搜索")
        self.btn_search = QPushButton("搜索标记")
        search_layout = QHBoxLayout()
        search_layout.addWidget(self.search_input)
        search_layout.addWidget(self.btn_search)

        self.lngLabel = QLabel("标记经度:")
        self.latLabel = QLabel("标记纬度:")
        self.biaojiLabel = QLabel("标记标题:")


        #布局
        self.layoutright.addLayout(search_layout)

        # 创建一个水平分割线
        v1_line = QFrame()
        v1_line.setFrameShape(QFrame.HLine)  # 设置为垂直线
        v1_line.setFrameShadow(QFrame.Sunken)  # 设置线条样式为下凹
        v1_line.setLineWidth(1)  # 设置线条宽度
        self.layoutright.addWidget(v1_line)

        self.layoutright.addWidget(self.lngLabel)
        self.layoutright.addWidget(self.input_lng)
        self.layoutright.addWidget(self.latLabel)
        self.layoutright.addWidget(self.input_lat)
        self.layoutright.addWidget(self.biaojiLabel)
        self.layoutright.addWidget(self.input_title)
        isok_layout = QHBoxLayout()
        isok_layout.addWidget(self.btn_add)
        isok_layout.addWidget(self.btn_clear)
        self.layoutright.addLayout(isok_layout)

        # 创建一个水平分割线
        v2_line = QFrame()
        v2_line.setFrameShape(QFrame.HLine)  # 设置为垂直线
        #v2_line.setStyleSheet("border: 1px solid black;")
        v2_line.setFrameShadow(QFrame.Sunken)  # 设置线条样式为下凹
        v2_line.setLineWidth(1)  # 设置线条宽度
        self.layoutright.addWidget(v2_line)

        datas_layout = QHBoxLayout()
        datas_layout.addWidget(self.btn_load)
        datas_layout.addWidget(self.btn_save)
        self.layoutright.addLayout(datas_layout)

        self.layoutright.addStretch(1)

        self.layout.addWidget(self.browser,1)
        self.layout.addLayout(self.layoutright,0)
        self.setCentralWidget(self.central_widget)
        
        # 绑定按钮事件
        self.btn_add.clicked.connect(self.add_marker)
        self.btn_clear.clicked.connect(self.clear_markers)
        self.btn_search.clicked.connect(self.search_marker)
        self.btn_save.clicked.connect(self.save_markers_to_file)
        self.btn_load.clicked.connect(self.load_markers_from_file)

        # 加载地图
        self.load_map()

    def search_marker(self):
        keyword = self.search_input.text()
        if keyword:
            keyword_escaped = keyword.replace("'", "\\'")
            js_code = f"searchMarkers('{keyword_escaped}')"
            self.browser.page().runJavaScript(js_code)

    def load_map(self):
        cur_path = Path.cwd() / "mymapmak.html"  # 拼接路径
        cur_path = str(cur_path)
        converted_path = cur_path.replace("\\", "/")
        self.browser.setUrl(f"file:///{converted_path}")
        #self.browser.setUrl(f"file:///F:/python/pyqttext/TowerDefect/mymapmak.html")

    def add_marker(self):
        lng = self.input_lng.text()
        lat = self.input_lat.text()
        title = self.input_title.text()
        if lng and lat:
            js_code = f"addMarker({lng}, {lat}, '{title}')"
            self.browser.page().runJavaScript(js_code)

    def clear_markers(self):
        self.browser.page().runJavaScript("clearMarkers()")

    def save_markers_to_file(self):
        self.browser.page().runJavaScript("exportMarkersToJSON()", 0, lambda result: self._save_to_file(result))

    def _save_to_file(self, json_data):
        if not json_data:
            print("无标记数据可保存")
            return
        
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存标记数据", "", "JSON Files (*.json)"
        )
        if not file_path:
            return
        
        try:
            with open(file_path, "w", encoding="utf-8") as f:
                f.write(json_data)
            print(f"保存成功：{file_path}")
        except Exception as e:
            print(f"保存失败：{e}")

    def load_markers_from_file(self):
        # 选择文件
        file_path, _ = QFileDialog.getOpenFileName(
            self, "加载标记数据", "", "JSON Files (*.json)"
        )
        if not file_path:
            return
        # 读取并加载数据
        with open(file_path, 'r', encoding='utf-8') as f:
            markers_data = json.load(f)
            for marker in markers_data:
                js_code = f"addMarker({marker['lng']}, {marker['lat']}, '{marker['title']}')"
                self.browser.page().runJavaScript(js_code)

if __name__ == "__main__":
    app = QApplication([])
    window = MapWindow()
    window.resize(800, 600)
    window.show()
    app.exec()